package cn.ctyun.ipush.controller;

import cn.ctyun.ipush.constant.ResultInfo;
import cn.ctyun.ipush.dto.ResultDto;
import cn.ctyun.ipush.model.EmailModel;
import cn.ctyun.ipush.service.EmailService;
import cn.ctyun.ipush.utils.DataUtils;
import cn.ctyun.ipush.utils.DateUtils;
import cn.ctyun.ipush.utils.EmailUtils;
import cn.ctyun.ipush.web.user.bo.UserModel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dexcoder.commons.utils.UUIDUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-7-4
 * Time: 上午10:41
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class EmailController {

    @Autowired
    private EmailService emailService;

    /* 日志对象 */
    private final Logger LOG = LoggerFactory.getLogger(EmailController.class);

    @RequestMapping(value = "emailIntoPage", method = RequestMethod.GET)
    public ModelAndView intoPage(HttpSession session, HttpServletRequest request) {

        UserModel systemUserModel = new UserModel();
        String msg = "";

        try {
            Object o = session.getAttribute("userInfo");
            if (o != null) {

                systemUserModel = (UserModel) o;

                //判断是否删除
                String method = request.getParameter("method");
                if (!StringUtils.isEmpty(method)) {
                    if (method.equals("delete")) {
                        String emailId = request.getParameter("emailId");
                        if (!StringUtils.isEmpty(emailId)) {
                            if (emailService.delete(emailId) == 0) {
                                msg = "该邮件规则在任务中有引用不能删除，请先删除任务，在进行删除";
                            }
                        }
                    }
                }

                List<EmailModel> list = new ArrayList<EmailModel>();

                //得到邮件
                EmailModel tmpEmailModel = new EmailModel();
                tmpEmailModel.setCreateUserid(systemUserModel.getUserModelId());
                List<EmailModel> emailModelList = emailService.queryList(tmpEmailModel);
                if (emailModelList != null) {
                    for (EmailModel emailModel : emailModelList) {
                        list.add(emailModel);
                    }
                }
                Map<String, Object> map = new LinkedHashMap<String, Object>();
                map.put("emailList", list);
                map.put("msg", msg);
                return new ModelAndView("emailManager", map);
            }
            return new ModelAndView("emailManager", null);
        } catch (Exception e) {
            e.printStackTrace();
            return new ModelAndView("emailManager", null);
        }
    }

    @RequestMapping(value = "checkEmailIsValid", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto checkDsTableIsExist(HttpServletRequest request) {
        String requestJsonParam = DataUtils.getJsonFromRequest(request);
        ResultDto resultDto = new ResultDto();
        if (StringUtils.isEmpty(requestJsonParam)) {
            return resultDto.setStatus(ResultInfo.failure).setInfo("测试邮箱连接失败，请检查参数是否配置正确");
        } else {
            try {
                JSONObject jsonObject = JSON.parseObject(requestJsonParam);
                String emailName = jsonObject.getString("emailName");
                String emailServer = jsonObject.getString("emailServer");
                String emailSubject=jsonObject.getString("emailSubject");
                String emailContent=jsonObject.getString("emailContent");
                String emailLoginName=jsonObject.getString("emailLoginName");
                String emailPassword=jsonObject.getString("emailPassword");
                //邮箱名称是否存在
                EmailModel emailModel=new EmailModel();
                emailModel.setEmailName(emailName);
                boolean isEmailExist=emailService.isExist(emailModel);
                if(isEmailExist){
                    return resultDto.setStatus(ResultInfo.failure).setInfo("邮件发送分组名已存在");
                }
                //邮箱是否可达
                emailModel.setEmailSender(emailLoginName);
                if (StringUtils.isEmpty(emailServer)) {
                    emailModel.setSmtpServer("smtp.189.cn");
//                    msg = "邮箱服务器名不为能空";
//                    isSave = false;
                } else {
                    emailModel.setSmtpServer(emailServer);
                }
                emailModel.setSmtpPort("25");
                emailModel.setEmailContent(emailContent);
                emailModel.setEmailSubject(emailSubject);
                emailModel.setEmailModelId(UUIDUtils.getUUID32());
                emailModel.setSmtpPassword(DataUtils.encodeString(emailPassword));
                emailModel.setSmtpUser(emailLoginName.split("@")[0]);
                emailModel.setEmailReceiversDb("junfei_www@163.com");
                boolean isEmailSendOk=EmailUtils.startMailSendTask(emailModel);
                if(!isEmailSendOk){
                    return resultDto.setStatus(ResultInfo.failure).setInfo("请检查发送邮箱名和密码是否配置正确");
                }

                return resultDto.setStatus(ResultInfo.success).setInfo("测试邮箱连接成功");

            } catch (Exception ex) {
                LOG.info("测试邮箱连接失败：" + ex.getMessage());
                return resultDto.setStatus(ResultInfo.failure).setInfo("请检查发送邮箱名和密码是否配置正确");
            }
        }
    }


    @RequestMapping(value = "emailIntoAdd", method = RequestMethod.POST)
    public ModelAndView emailIntoAdd(HttpSession session, HttpServletRequest request) {

        UserModel systemUserModel = new UserModel();
        String msg = "";
        EmailModel emailModel = new EmailModel();
        try {
            Object o = session.getAttribute("userInfo");

            if (o != null) {
                systemUserModel = (UserModel) o;
                boolean isSave = true;

                List<EmailModel> list = new ArrayList<EmailModel>();
                //判断邮件属性是否为空
                String emailName = request.getParameter("emailName");
                if (StringUtils.isEmpty(emailName)) {
                    msg = "邮件规则名不为能空";
                    isSave = false;
                } else {
                    emailModel.setEmailName(emailName);
                }

                String emailServer = request.getParameter("emailServer");
                if (StringUtils.isEmpty(emailServer)) {
                    emailModel.setSmtpServer("smtp.189.cn");
//                    msg = "邮箱服务器名不为能空";
//                    isSave = false;
                } else {
                    emailModel.setSmtpServer(emailServer);
                }

                String emailLoginName = request.getParameter("emailLoginName");
                if (StringUtils.isEmpty(emailLoginName)) {
                    msg = "邮箱服务器用户名不为能空";
                    isSave = false;
                } else {
                    emailModel.setSmtpUser(emailLoginName.split("@")[0]);
                    emailModel.setEmailSender(emailLoginName);
                }

                String emailPassword = request.getParameter("emailPassword");
                if (StringUtils.isEmpty(emailPassword)) {
                    msg = "邮箱服务器密码不为能空";
                    isSave = false;
                } else {
                    emailModel.setSmtpPassword(DataUtils.encodeString(emailPassword));
                }

                String emailSubject = request.getParameter("emailSubject");
                if (StringUtils.isEmpty(emailSubject)) {
                    msg = "邮件主题不为能空";
                    isSave = false;
                } else {
                    emailModel.setEmailSubject(emailSubject);
                }

                //测试邮件发送人是否配置正确
                try{
                    emailModel.setEmailModelId(UUIDUtils.getUUID32());
                    emailModel.setEmailReceiversDb("junfei_www@163.com");
                    emailModel.setSmtpPort("25");
                    if(!EmailUtils.startMailSendTask(emailModel)){
                        msg = "邮件发送人邮箱和密码错误";
                        isSave = false;
                    }
                }catch (Exception ex){
                    msg = "邮件发送人邮箱和密码错误";
                    isSave = false;
                }

                String emailContent = request.getParameter("emailContent");
                emailModel.setEmailContent(emailContent);

                //保存邮件信息到DB
                if (isSave) {
                    //邮件规则名称不能为已经存在的
                    if (!emailService.isExist(emailModel)) {
                        emailModel.setEmailReceiversDb("");
                        emailModel.setCreateUserid(systemUserModel.getUserModelId());
                        emailModel.setCreateDate(DateUtils.dateToString(new Date()));
                        emailModel.setIsDeleted("0");
                        emailModel.setSmtpPort("25");
                        emailService.save(emailModel);
                    } else {
                        msg = "邮件规则名称已存在";
                    }
                }

                //得到邮件
                EmailModel tmpEmailModel = new EmailModel();
                tmpEmailModel.setCreateUserid(systemUserModel.getUserModelId());
                List<EmailModel> emailModelList = emailService.queryList(tmpEmailModel);
                if (emailModelList != null) {
                    for (EmailModel emailModelTmp : emailModelList) {
                        list.add(emailModelTmp);
                    }
                }

                Map<String, Object> map = new LinkedHashMap<String, Object>();
                map.put("emailList", list);
                map.put("msg", msg);
                return new ModelAndView("emailManager", map);
            } else {
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            return new ModelAndView("login", null);
        }
    }

    /**
     * 加载TABLE，显示数据并且4个一行显示
     */
    @RequestMapping(value = "loadPutEmailName", method = RequestMethod.GET)
    public ModelAndView loadPutEmailName(HttpSession session, HttpServletRequest request) {

        UserModel systemUserModel = new UserModel();
        try {
            Object o = session.getAttribute("userInfo");
            if (o != null) {

                systemUserModel = (UserModel) o;///得到USER

                String emailId = request.getParameter("emailId");//得到这个database 名字

                //是否删除接收人
                String[] tableNameLists = request.getParameterValues("tableNameList");
                if (null != tableNameLists) {
                    EmailModel emailModel = emailService.querySingleResult(emailId);
                    String receiversDb = emailModel.getEmailReceiversDb();
                    String resultTable = "";
                    for (String receiver : receiversDb.split("\\$")) {
                        boolean isExist = false;
                        for (String tmpTable : tableNameLists) {
                            if (receiver.equals(tmpTable)) {
                                isExist = true;
                                break;
                            }
                        }
                        if (!isExist) {
                            resultTable += (receiver + "$");
                        }
                    }
                    if (!resultTable.equals("")) {
                        resultTable = resultTable.substring(0, resultTable.length() - 1);
                    }
                    emailModel.setEmailReceiversDb(resultTable);
                    emailService.update(emailModel);
                }

                // create user + dataname 确定一个 datasource
                //查出来这个datasource所有的tablename
                List<String> tableList = new ArrayList<String>();
                EmailModel emailModel = emailService.querySingleResult(emailId);
                String emailReceiversDb = emailModel.getEmailReceiversDb();
                List<List<String>> resultList = new ArrayList<List<String>>();
                if (null != emailReceiversDb) {
                    for (String receiver : emailReceiversDb.split("\\$")) {
                        tableList.add(receiver);
                    }
                    //组成一个二维数据
                    List<String> siteList = null;
                    for (int i = 0; i < tableList.size(); i++) {
                        if (i % 4 == 0) {
                            if (i != 0) {
                                resultList.add(siteList);
                            }
                            siteList = new ArrayList<String>();
                            siteList.add(tableList.get(i));
                        } else {
                            siteList.add(tableList.get(i));
                        }
                    }
                    resultList.add(siteList);
                }

                Map<String, Object> data = new HashMap<String, Object>();
                data.put("tableName", resultList);
                data.put("emailId", emailId);
                return new ModelAndView("emailEmailPuter", data);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }
    }

    @RequestMapping(value = "addPutEmailName", method = RequestMethod.POST)
    public ModelAndView addPutEmailName(HttpSession session, HttpServletRequest request, RedirectAttributes attr) {

        UserModel systemUserModel = new UserModel();
        String tableAddMsg = "";
        try {
            Object o = session.getAttribute("userInfo");
            if (o != null) {

                systemUserModel = (UserModel) o;///得到USER
                String emailId = request.getParameter("emailId");//得到这个database 名字
                //查出来这个datasource所有的tablename
                List<String> tableList = new ArrayList<String>();

                //判断接收人是否为空
                String addReceiver = request.getParameter("addReceiver");
                EmailModel emailModel = emailService.querySingleResult(emailId);

                if (StringUtils.isEmpty(addReceiver)) {
                    tableAddMsg = "增加的接收人为空";
                } else {
                    //增加这个表到DB
                    String receivers = emailModel.getEmailReceiversDb();
                    if (receivers == null) {
                        emailModel.setEmailReceiversDb(addReceiver);
                        emailService.update(emailModel);
                    } else {
                        //判断表名是否重复
                        boolean isReceiverNameSame = false;
                        for (String existReceiverName : receivers.split("\\$")) {
                            if (existReceiverName.equals(addReceiver)) {
                                isReceiverNameSame = true;
                                break;
                            }
                        }
                        if (!isReceiverNameSame) {
                            emailModel.setEmailReceiversDb(receivers + "$" + addReceiver);
                            emailService.update(emailModel);
                        } else {
                            tableAddMsg = "增加的接收人已经存在";
                        }
                    }
                }

                //得到邮件接收人
//                EmailModel emailModelTmp=emailService.querySingleResult(emailId);
//                String emailReceiversDb=emailModelTmp.getEmailReceiversDb();
//                List<List<String>> resultList = new ArrayList<List<String>>();
//                if(null!=emailReceiversDb){
//                    for(String receiver:emailReceiversDb.split("\\$")){
//                        tableList.add(receiver);
//                    }
//                    //组成一个二维数据
//                    List<String> siteList =null;
//                    for(int i=0;i<tableList.size();i++){
//                        if(i%4==0){
//                            if(i!=0){
//                                resultList.add(siteList);
//                            }
//                            siteList = new ArrayList<String>();
//                            siteList.add(tableList.get(i));
//                        }
//                        else{
//                            siteList.add(tableList.get(i));
//                        }
//                    }
//                    resultList.add(siteList);
//                }
//
//                Map<String,Object> data = new HashMap<String,Object>();
//                data.put("tableName",resultList);
//                data.put("emailId",emailId);
//                data.put("msg",tableAddMsg);
                //得到邮件
                List<EmailModel> list = new ArrayList<EmailModel>();
                EmailModel tmpEmailModel = new EmailModel();
                tmpEmailModel.setCreateUserid(systemUserModel.getUserModelId());
                List<EmailModel> emailModelList = emailService.queryList(tmpEmailModel);
                if (emailModelList != null) {
                    for (EmailModel emailModel1 : emailModelList) {
                        list.add(emailModel1);
                    }
                }
                Map<String, Object> map = new LinkedHashMap<String, Object>();
                map.put("emailList", list);
                map.put("msg", tableAddMsg);
                return new ModelAndView("emailManager", map);
            } else {
                //没有登录。。。。跳回login
                return new ModelAndView("login", null);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
            //没有登录。。。。跳回login
            return new ModelAndView("login", null);
        }
    }
}
